package com.group7.mall.redis;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 
/**
 * 分布式锁
 * @author wuweifeng wrote on 2019/5/8.
 */

@Aspect
@Component
@Order(1) // 设置Aspect的执行顺序
public class RedissonLockAspect {
    private static final Logger log = LoggerFactory.getLogger(RedissonLockAspect.class);
    @Resource
    private RedissonClient redissonClient;

    @Around("execution(* com.group7.mall.service.impl.UserOrderServiceImpl.*(..)) && @annotation(redissonLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedissonLock redissonLock) throws Throwable {
        Object obj = null;

        // 自定义的锁key
        String key = "goodsOperation";

        // 多久会自动释放，默认10秒
        int leaseTime = redissonLock.leaseTime();
        int waitTime = 1;

        RLock rLock = redissonClient.getLock(key);
        boolean res = rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        if (res) {
            log.info("取到锁");
            try {
                obj = joinPoint.proceed();
            } finally {
                rLock.unlock();
                log.info("释放锁");
            }
        } else {
            log.info("----------nono----------");
            throw new RuntimeException("没有获得锁");
        }
        return obj;
    }
}